package com.xiaobange.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xiaobange.constants.RedisKey;
import com.xiaobange.dto.UserPage;
import com.xiaobange.entity.User;
import com.xiaobange.exception.ServiceException;
import com.xiaobange.service.UserService;
import com.xiaobange.mapper.UserMapper;
import com.xiaobange.utils.PasswordUtil;
import com.xiaobange.utils.RedisCache;
import com.xiaobange.utils.ResponseCodeEnum;
import com.xiaobange.vo.ResultResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author banji
 * @description 针对表【sys_user(系统用户表)】的数据库操作Service实现
 * @createDate 2025-04-24 17:57:21
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
        implements UserService {

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private UserMapper userMapper;

    /**
     * 分页查询系统用户数据
     *
     * @param userPage 参数
     * @return 分页结果
     */
    @Override
    public ResultResponse<List<User>> selectPage(UserPage userPage) {
        //从redis中查询缓存
        int pageStart = (userPage.getCurrent() - 1) * userPage.getSize();
        String key = pageStart + userPage.getSize() + userPage.getUsername() + userPage.getRole();
        List<User> listCache = redisCache.getCacheObject(RedisKey.USER_INFO_PAGE_KEY + key);
        if (listCache != null) {
            return ResultResponse.success(listCache);
        }
        // 从数据库中查询数据
        userPage.setCurrent(pageStart);
        List<User> userList = userMapper.userPage(userPage);
        //  将分页数据保存到Redis
        redisCache.setCacheObject(RedisKey.USER_INFO_PAGE_KEY + key, userList, 5, TimeUnit.MINUTES);
        //返回分页数据
        return ResultResponse.success(userList);
    }

    /**
     * 根据用户ID查询用户数据
     *
     * @param userid 用户ID
     * @return 用户数据
     */
    @Override
    public User queryId(String userid) {
        if (userid.isEmpty()){
            //如果ID等于空就查询自己的信息
            userid = StpUtil.getLoginId().toString();
        }
        //查询redis缓存是否存在信息
        User userCache = redisCache.getCacheObject(RedisKey.USER_INFO_ID_KEY + userid);
        if (userCache != null) {
            return userCache;
        }
        User user = userMapper.queryUserById(userid);
        if (user == null) {
            throw new ServiceException(ResponseCodeEnum.SERVER_ERROR.getCode(), "未查询到该用户信息!");
        }
        user.setPassword("**************");
        //将数据缓存到redis
        redisCache.setCacheObject(RedisKey.USER_INFO_ID_KEY + userid, user, 60, TimeUnit.MINUTES);
        return user;
    }

    /**
     * 修改用户数据
     *
     * @param user 被修改的用户数据
     * @return 结果
     */
    String USER_ROLE_ADMIN = "admin";
    @Override
    public ResultResponse<String> updateInfo(User user) {
        // 只能修改自己的信息，管理员可以修改所有人的数据
        String loginId = StpUtil.getLoginId().toString();
        String role = StpUtil.getExtra("role").toString();
        if (!loginId.equals(user.getUserId().toString()) && !role.equals(USER_ROLE_ADMIN)){
            throw new ServiceException(ResponseCodeEnum.FORBIDDEN.getCode(),ResponseCodeEnum.FORBIDDEN.getMessage());
        }
        user.setUpdateTime(LocalDateTime.now());
        user.setPassword(null);
         user.setUpdateBy(loginId);
        int count = userMapper.updateInfo(user);
        if (count > 0) {
            //更新Redis中的数据
            redisCache.setCacheObject(RedisKey.USER_INFO_ID_KEY + user.getUserId(), user, 30, TimeUnit.MINUTES);
            return ResultResponse.success();
        }
        return ResultResponse.error(500, "修改失败!");
    }

    /**
     * 修改密码
     *
     * @param userId   用户ID
     * @param password 新密码
     * @return
     */
    @Override
    public ResultResponse<?> updatePassword(String userId, String password) {
        User user = userMapper.queryUserById(userId);
        if (user == null)
            return ResultResponse.error(ResponseCodeEnum.NOT_FOUND.getCode(), "用户不存在!");
        //对新密码进行加密
        user = new User();
        String passwordEncryption = PasswordUtil.passwordEncryption(password);
        user.setUserId(Integer.valueOf(userId));
        user.setPassword(passwordEncryption);
        user.setPwdUpdateDate(LocalDateTime.now());
        // 修改
        int count = userMapper.updatePassword(user);
        if(count < 0){
            return ResultResponse.error(ResponseCodeEnum.SERVER_ERROR.getCode(), "更新密码失败!");
        }
        //需要让用户重新登录
//        StpUtil.logout();
        return ResultResponse.success("更改密码成功!");
    }


    /**
     * 删除系统用户
     * @param userId 用户ID
     * @return
     */
    @Override
    public ResultResponse<Integer> delById(String userId) {
        //先查询该用户是否为管理员，管理员不能删除
        User user = userMapper.queryUserById(userId);
        if (user  == null){
            return ResultResponse.error(ResponseCodeEnum.NOT_FOUND.getCode(),"用户不存在");
        }
        if ("100".equals(user.getRoleId().toString())){
            return ResultResponse.error(ResponseCodeEnum.FORBIDDEN.getCode(),"无权删除管理员!");
        }
        user = new User();
        user.setUserId(Integer.valueOf(userId));
        user.setUpdateTime(LocalDateTime.now());
        user.setDelFlag("1");
        int count = userMapper.updateInfo(user);
        if (count > 0){
            //删除Redis中的缓存
            redisCache.deleteObject(RedisKey.USER_INFO_ID_KEY + userId);
        }
        return ResultResponse.success();
    }
}




